package com.listtest;

import java.util.ArrayList;

//向ArrayList里面添加自定义类对象 并查找集合里面重复的元素，将不重复的元素存入新的集合中
//ArrayList中contains方法的底层使用了equals方法 所以要给自定义类重写equals方法.
//System.out.println(arr); 底层调用了toString方法 所以要重写自定义类的toString方法
public class ArrayListTest {
    public static void main(String[] args) {
        ArrayList arr = new ArrayList();
        ArrayList brr = new ArrayList();
        Person p1 = new Person(10,"Tom","man");
        Person p2 = new Person(10,"Tom","woman");
        Person p3 = new Person(30,"Lucy","woman");
        Person p4 = new Person(30,"Lucy","man");
        Person p5 = new Person(30,"Lucy","man");
        arr.add(p1);
        arr.add(p2);
        arr.add(p3);
        arr.add(p4);
        arr.add(p5);
        System.out.println(arr);
        for (int i = 0; i < arr.size(); i++) {
            //多态 Object obj = p1;
            Object obj = arr.get(i);
            Person p = (Person)obj;
            if(!brr.contains(p)){
                brr.add(arr.get(i));
            }
        }
        System.out.println(brr);
    }
}
class Person{
    private int age;
    private String name;
    private String sex;
    public Person(int age,String name,String sex){
        this.age = age;
        this.name = name;
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "Person{" +
                "age=" + age +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Person person = (Person) o;

        if (age != person.age) return false;
        if (name != null ? !name.equals(person.name) : person.name != null) return false;
        return sex != null ? sex.equals(person.sex) : person.sex == null;
    }

}
